package com.prototype.deepclone.self;

import java.io.*;

public class DeepCopyType implements Serializable,Cloneable {

    private String name;

    private DeepCopyTarget deepCopyTarget;

    public DeepCopyType(String name, DeepCopyTarget deepCopyTarget) {
        this.name = name;
        this.deepCopyTarget = deepCopyTarget;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepCopyType deepCopyType=(DeepCopyType) super.clone();
        deepCopyType.deepCopyTarget=(DeepCopyTarget) deepCopyTarget.clone();
        return deepCopyType;
    }

    public Object getClone(){
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        DeepCopyType object = null;
        try {
           byteArrayOutputStream = new ByteArrayOutputStream();
           objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
           objectOutputStream.writeObject(this);

           byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
           objectInputStream = new ObjectInputStream(byteArrayInputStream);
           object = (DeepCopyType) objectInputStream.readObject();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
                byteArrayOutputStream.close();
                objectInputStream.close();
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("创建对象失败");
            }
        }
        return object;
    }
}
